package org.example.configcenter;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class FetchConfigFromRemote {

    public static String fetch(String url, String token) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("GET"); // 或 POST
        conn.setRequestProperty("Authorization", "Bearer " + token); // 带 Token
        conn.setRequestProperty("Content-Type", "application/json");

        // 如果是 POST 请求
        // conn.setDoOutput(true);
        // try (OutputStream os = conn.getOutputStream()) {
        //     os.write("{\"key\":\"value\"}".getBytes(StandardCharsets.UTF_8));
        // }

        int responseCode = conn.getResponseCode();
        InputStream inputStream;
        if(responseCode >=200 && responseCode <300){
            inputStream = conn.getInputStream();
        } else {
            inputStream = conn.getErrorStream();
        }

        String result = null;
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
            result = response.toString();
        }

        if(responseCode >=200 && responseCode <300){
            return result;
        } else {
            throw new RuntimeException("require fail, response:" + result);
        }
    }
}
